/* ClientSocket.h
 *
 * --
 * Copyright (c) 2012, Christophe Huriaux
 * Distributed under the terms of the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * --
 */

#ifndef CLIENTSOCKET_H
#define CLIENTSOCKET_H

#include <string>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <thread/thread.h>

#define CLIENTSOCKET_IO_BUFFER_SIZE	64*(1024)
#define CLIENTSOCKET_DEBUG				0

class ClientSocket : public Thread
{
	std::string 			serverName;
	std::string				serverNameResolved;
	unsigned short int	serverPort;

	struct sockaddr_in 		serverSockAddr;
	struct hostent*			serverHostent;
	int						sock;

	pthread_mutex_t			ioMutex;

	char					recvBuffer[CLIENTSOCKET_IO_BUFFER_SIZE];
	unsigned long			recvBufferBegin;
	unsigned long			recvBufferNext;
	bool					recvBufferEmpty;
	bool					recvBufferFull;



public:
	ClientSocket(const char* serverName, unsigned short int port);
	~ClientSocket();

	int resolve();
	int open();
	int close();

protected:
	void* run();
	void atCleanup();

public:
	int count();
	int remaining();
	std::string read(int length);
	ssize_t read(void* buffer, ssize_t count);
	int write(const void* buffer, size_t count);

	// Getters & setters
	const char* getServerName();
	void setServerName(const char* serverName);
	const char* getResolvedServerName();

	bool isIoThreadRunning();

private:
	int setNonBlock(bool nonblock);
};

#endif
